#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "iconv.h"

//iInLen的长度不包括\0，应该用strlen。返回值是处理后的sOut长度
int Utf8ToGb2312(char *sOut, int iMaxOutLen, const char *sIn, int iInLen)
{
    char *pIn = (char *)sIn;
    char *pOut = sOut;
    size_t ret;
    size_t iLeftLen=iMaxOutLen;
    iconv_t cd;

    //cd = iconv_open("gb2312", "utf-8");
    cd = iconv_open("win_1250", "win_1251");

    if (cd == (iconv_t) - 1)
    {
        return -1;
    }
	
    size_t iSrcLen=iInLen;
    ret = iconv(cd, &pIn,&iSrcLen, &pOut,&iLeftLen);
	
    if (ret == (size_t) - 1)
    {
        iconv_close(cd);
        return -1;
    }

    iconv_close(cd);

    return (iMaxOutLen - iLeftLen);
}

//iInLen的长度不包括\0，应该用strlen。返回值是处理后的sOut长度
int Gb2312ToUtf8(char *sOut, int iMaxOutLen, const char *sIn, int iInLen)
{
    char *pIn = (char *)sIn;
    char *pOut = sOut;
    size_t ret;
    size_t iLeftLen=iMaxOutLen;
    iconv_t cd;


    //cd = iconv_open("utf-8", "gb2312");
    cd = iconv_open("win_1251", "win_1250");
	
    if (cd == (iconv_t) - 1)
    {
        return -1;
    }
    size_t iSrcLen=iInLen;
	
    ret = iconv(cd, &pIn,&iSrcLen, &pOut,&iLeftLen);
    if (ret == (size_t) - 1)
    {
        iconv_close(cd);
        return -1;
    }

    iconv_close(cd);

    return (iMaxOutLen - iLeftLen);
}

int CharacterencodingTransfTest(void)
{
	int nRtn = 0;
	char* pszOri = "这是一个中文测试例程";

	printf("byStr[%d]: %s\n", strlen(pszOri), pszOri);
    
    char pszDst[50] = {0};
    
    int iLen = Utf8ToGb2312(pszDst, 50, pszOri, strlen(pszOri)); // Utf8ToGb2312

	printf("iLen: %d    %s\n", iLen, pszDst);

	printf("-----------\n");
    
    char pszGbDst[50] = {0};  
    int iNewLen = Gb2312ToUtf8(pszGbDst, 50, pszDst, iLen); // Gb2312ToUtf8  

	printf("iNewLen: %d    %s\n", iNewLen, pszGbDst);

	return nRtn;
}
